這邊也是直接參照Nuxt i18n官網,我覺得他文件寫得滿好的,照做沒毛病~
再提一下,由於這個專案的產品資料是拿dummyData現成的,只有英文,而我也沒打算出中文的,所以只會拿UI相關的文字整理起來做語言切換。只有中、英文兩個語言。
vue-i18n
老話一句,看官網
npx nuxi@latest module add i18n
nuxt.config.ts
的modules
也會被更新上去:
export default defineNuxtConfig({
...
modules: ['@pinia/nuxt', '@nuxtjs/i18n'],
...
})
./lang/en.js
, ch.js
,這是要放中英文版本的文字。i18n
的部分:// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
...
i18n: {
vueI18n: './i18n.config.ts'
},
})
// ./lang/ch.js
export default {
category: "分類",
member: {
login: "登入",
notMem: "還不是會員?",
signup:"註冊",
hadAnAcc:"已經有帳號?"
},
prod:{
left:"剩下",
search:"搜尋",
review:"回應",
addToCart: "加到購物車",
purchaseOrder:"結帳",
limit:"已達到購買上限"
}
}
// ./lang/en.js
export default {
category: "category",
member: {
login: "login",
notMem: "not a member yet?",
signup:"registration",
hadAnAcc:"already have an account?"
},
prod:{
left:"left",
search:"search",
review:"reviews",
addToCart: "add to cart",
purchaseOrder:"purchase order",
limit:"Purchase limit reached"
}
}
拿"category"來測試,構想是在./pages/index.vue
新增下拉選單切換語言:
<script setup lang="ts">
...
const { locale, setLocale, availableLocales } = useI18n();
...
// 當前選擇的語言
const selectedLang = ref(locale.value)
// 切換語言的方法
const switchLan = (event: Event) => {
if(event.target) {
const newLanguage = event.target.value;
locale.value = newLanguage;
}
};
</script>
<template>
<div>
Page: index
<select v-model="selectedLang" @change="switchLan($event)">
<option v-for="lc in availableLocales" :value="lc">{{ lc }}</option>
</select>
{{ $t('category') }}
</div>
</template>
<style scoped>
</style>
然後切換語言~成果長這樣: